package com.rz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.admin.entity.Res;
import com.rz.admin.entity.RoleResource;
import com.rz.admin.mapper.ResourceMapper;
import com.rz.admin.service.IResService;
import com.rz.admin.service.IRoleResService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ResService extends ServiceImpl<ResourceMapper, Res> implements IResService {

    @Resource private IRoleResService roleResService;

    @Override
    public List<Res> buildResTree(List<Res> resList) {
        List<Res> ress = resList.stream().filter(res -> res.getParentId().equals(0)).collect(Collectors.toList());
        ress.forEach(res -> {
            buildResChildren(res, resList);
        });
        return ress;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean onSave(Res res) {
        boolean ok;
        if(res.getId()!=null){
            ok = updateById(res);
        }else{
            ok = save(res);
            if(ok){
                RoleResource roleResource = new RoleResource(1,res.getId(),0);
                roleResService.saveOrUpdate(roleResource);
            }
        }
        return ok;
    }

    @Override
    public List<Res> listIdsWarpper(List<Integer> ids, boolean showBtn) {
        QueryWrapper<Res> resQueryWrapper = new QueryWrapper<>();
        resQueryWrapper.in("id",ids);
        if(!showBtn){
            resQueryWrapper.notIn("type",3);
        }
        return list(resQueryWrapper);
    }

    private void buildResChildren(Res res, List<Res> resList) {
        List<Res> children;
        children = resList.stream().filter(res1 -> res1.getParentId().equals(res.getId())).sorted(Comparator.comparing(Res::getSortBy)).collect(Collectors.toList());
        if (children.size() > 0) {
            children.forEach(res1 -> {
                res1.setParentName(res.getName());
                buildResChildren(res1, resList);
            });
        }
        res.setChildren(children.size() > 0 ? children : null);
    }
}
